package com.lagou.common.zk;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.List;


public class ZooKeeperHelper {

    private static final String ZOOKEEPER_CONNECT = "127.0.0.1:2181";
    private static CuratorFramework client;

    static {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.builder()
                .connectString(ZOOKEEPER_CONNECT)
                .sessionTimeoutMs(300) // 默认60000
                .connectionTimeoutMs(100) // 默认15000
                .retryPolicy(retryPolicy)
                .namespace("lagou")
                .build();
        client.start();
    }

    public static void createNode(String path, byte[] data, CreateMode createMode) throws Exception {

        Stat stat = client.checkExists().forPath(path);
        if (stat != null) {
            client.delete().guaranteed().forPath(path);
        }

        client.create().creatingParentsIfNeeded().withMode(createMode).forPath(path, data);
    }

    public static List<String> getChildren(String path) throws Exception {
        return client.getChildren().forPath(path);
    }

    public static byte[] getData(String path) throws Exception {
        return client.getData().forPath(path);
    }

    public static Stat getStat(String path) throws Exception {
        Stat stat = new Stat();
        client.getData().storingStatIn(stat).forPath(path);
        return stat;
    }

    public static void setData(String path, byte[] data) throws Exception {
        client.setData().forPath(path, data);
    }

    public static CuratorFramework getClient() {
        return client;
    }
}
